package com.example.smartgreenhouse.controller;

import com.example.smartgreenhouse.entity.DeviceCurrent;
import com.example.smartgreenhouse.annotation.JwtToken;
import com.example.smartgreenhouse.annotation.Limit;
import com.example.smartgreenhouse.entity.FanOperationLog;
import com.example.smartgreenhouse.exception.BusinessException;
import com.example.smartgreenhouse.service.DeviceCurrentService;
import com.example.smartgreenhouse.service.FanService;
import com.example.smartgreenhouse.utils.ResponseWrapper;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/gsas/api/v1/device/fan")
@RequiredArgsConstructor
public class FanController {

    @Autowired
    private final FanService fanService;

    private final DeviceCurrentService deviceCurrentService;
    @PostMapping("/auto_control")
    @JwtToken
    @Limit(
            key = "setFanAutoControl",                      // 限流标识（通常作为Key）
            permitsPerSecond = 3.0,                 // 每秒许可数
            timeout = 1000,                         // 尝试获取令牌的等待时间（毫秒）
            limitType = Limit.LimitType.IP,        // 限流策略（按IP限流）
            msg = "请求过于频繁，请稍后再试."      // 超限后的提示信息
    )
    public ResponseEntity<?> autoControlFan(@RequestBody @Valid AutoFanControlRequest request){
        try {
            // 处理默认值
            Long fanId = request.getFanId() != null ? request.getFanId() : 2L;
            Long greenhouseId = request.getGreenhouseId() != null ? request.getGreenhouseId() : 1L;
            Long operatorId = request.getOperatorId()!=null ? request.getOperatorId() : 1L;
            Integer action = request.getAction();

            Map<String,Object> operationLog = fanService.setFanAuto(fanId,greenhouseId,operatorId,action);
            return ResponseEntity.ok(operationLog);
        } catch (BusinessException e) {
            return ResponseEntity.badRequest()
                    .body(ResponseWrapper.badRequest(e.getMessage()));
        }
    }
    @PostMapping("/control")
    @JwtToken
    @Limit(
            key = "controlFan",                          // 限流标识（通常作为Key）
            permitsPerSecond = 3.0 ,                 // 每秒许可数
            timeout = 1000,                         // 尝试获取令牌的等待时间（毫秒）
            limitType = Limit.LimitType.IP,        // 限流策略（按IP限流）
            msg = "请求过于频繁，请稍后再试."      // 超限后的提示信息
    )
    public ResponseEntity<ResponseWrapper<?>> controlFan(
            @RequestBody @Valid FanControlRequest request) {
        try {
            // 处理默认值
            Long fanId = request.getFanId() != null ? request.getFanId() : 1L;
            Long greenhouseId = request.getGreenhouseId() != null ? request.getGreenhouseId() : 1L;
            Long operatorId = request.getOperatorId() != null ? request.getOperatorId() : 1L;

            FanOperationLog operationLog = fanService.controlFan(
                    fanId,
                    greenhouseId,
                    request.getLevel(),
                    operatorId
            );

            return ResponseEntity.ok(ResponseWrapper.success( "设置风扇挡位成功",operationLog));
        } catch (BusinessException e) {
            return ResponseEntity.badRequest()
                    .body(ResponseWrapper.badRequest(e.getMessage()));
        }
    }

    @GetMapping("/current")
    @Limit(
            key = "Fan_current",                          // 限流标识（通常作为Key）
            permitsPerSecond = 30.0 / 60.0,                 // 每秒许可数
            timeout = 500,                         // 尝试获取令牌的等待时间（毫秒）
            limitType = Limit.LimitType.IP,        // 限流策略（按IP限流）
            msg = "请求过于频繁，请稍后再试."      // 超限后的提示信息
    )
    public ResponseEntity<ResponseWrapper<?>> getFanCurrentStatus(
            @RequestParam Long fanId) {
        try{
            DeviceCurrent fanCurrent = deviceCurrentService.getDeviceStatus("fan", fanId);
            return ResponseEntity.ok(ResponseWrapper.success(
                    fanId+"号风扇的状态获取成功",fanCurrent));
        } catch (BusinessException e) {
            return ResponseEntity.badRequest()
                    .body(ResponseWrapper.badRequest(e.getMessage()));
        }
    }


    @GetMapping("/history/{fanId}")
    @JwtToken
    @Limit(
            key = "getFanHistoryOperation",                          // 限流标识（通常作为Key）
            permitsPerSecond = 3.0 ,                 // 每秒许可数
            timeout = 1000,                         // 尝试获取令牌的等待时间（毫秒）
            limitType = Limit.LimitType.IP,        // 限流策略（按IP限流）
            msg = "请求过于频繁，请稍后再试."      // 超限后的提示信息
    )
    public ResponseEntity<ResponseWrapper<?>> getFanHistory(
            @PathVariable Long fanId) {
        try {
            List<FanOperationLog> history = fanService.getFanHistory(fanId);
            return ResponseEntity.ok(ResponseWrapper.success("查询风扇操作历史记录成功",history));
        } catch (BusinessException e) {
            return ResponseEntity.badRequest()
                    .body(ResponseWrapper.badRequest(e.getMessage()));
        }
    }

    @Data
    public static class FanControlRequest {
        private Long fanId;
        private Long greenhouseId;
        
        @NotNull(message = "风扇档位不能为空")
        private String level;

        private Long operatorId;
    }

    @Data
    public static class AutoFanControlRequest {
        private Long fanId;
        private Long greenhouseId;
        @NotNull(message = "操作动作不能为空")
        private Integer action; // 0 关闭自动灌溉，1 开启自动灌溉
        private Long operatorId;
    }
}